import React, { useState, cloneElement, isValidElement, Children } from 'react';
import { Card } from 'antd';
import { router, withRouter } from 'umi';
import PropTypes from 'prop-types';

const emp = { key: 'unexceped', tab: 'unExcepedTabList' };
const HistoryTabCard = ({
    location,
    tabList = [emp],
    defaultActiveTabKey,
    children,
    onBeforeTabChange,
    onTabChange,
    ...rests
}) => {
    const { query } = location;
    const { currTab = defaultActiveTabKey || tabList[0].key } = query;
    const [lastQuery, setLastQuery] = useState({});
    const handleTabChange = key => {
        if (onBeforeTabChange && !onBeforeTabChange(key)) {
            return;
        }
        setLastQuery({ [currTab]: { ...query } });
        if (onTabChange) onTabChange(key);
        history.push({
            query: {
                ...lastQuery[key],
                currTab: key
            }
        });
    };
    const currChild = () => {
        let ret = Children.toArray(children)
            .filter(child => isValidElement(child))
            .map(child => cloneElement(child, { location }));
        const tabKeys = ret.map((_, index) => (tabList[index] && tabList[index].key) || index);
        // 非自定义时，默认增加控制隐藏显示逻辑
        if (!onTabChange) {
            ret = ret[tabKeys.findIndex(tab => tab === currTab)] || '';
        }
        return ret;
    };
    return (
        <Card {...rests} bordered={false} tabList={tabList} onTabChange={handleTabChange} activeTabKey={currTab}>
            {currChild()}
        </Card>
    );
};
HistoryTabCard.propTypes = {
    tabList: PropTypes.array.isRequired
};

export default withRouter(HistoryTabCard);
